package impl.service;

import tools.FilePath;

import javax.sound.sampled.UnsupportedAudioFileException;
import java.io.DataInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.sql.SQLException;

public class UploadServer {
    private ServerSocket serverSocket = null;

    public UploadServer(int port) throws IOException {
            serverSocket = new ServerSocket(port);
            System.out.println("音乐上传服务器");
    }
    public void start() {
        while (true) {
            try {
                Socket clientSocket = serverSocket.accept();
                System.out.println("客户端连接成功：" + clientSocket);
                // 创建输入流
                DataInputStream dis = new DataInputStream(clientSocket.getInputStream());
                // 读取文件名
                String fileName = dis.readUTF();
                long fileSize = dis.readLong();
                // 创建输出流，将接收的文件写入
                System.out.println("fileName:" + fileName);
                FileOutputStream fos = new FileOutputStream(FilePath.URL + fileName);
                byte[] buffer = new byte[4096];
                int bytesRead;
                long totalBytesRead = 0;
                while (totalBytesRead < fileSize && (bytesRead = dis.read(buffer, 0, (int) Math.min(buffer.length, fileSize - totalBytesRead))) != -1) {
                    fos.write(buffer, 0, bytesRead);
                    totalBytesRead += bytesRead;
                }
                System.out.println("文件上传完成");
                fos.close();
                try {
                    UploadSql.upload(fileName);
                } catch (UnsupportedAudioFileException e) {
                    throw new RuntimeException(e);
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
                clientSocket.close();

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
